﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using NHibernate;
using Inovout.Repositories;
using Inovout.Cloud.DataStore.Models;

namespace Inovout.Cloud.DataStore.Repositories
{
    public class DatabaseRepository : DataObjectRepository<Database>
    {
        public override void Delete(Database database)
        {
            using (ISession session = OpenSession())
            {
                //先删除与它关联的所有DataCollection
                string hql = "from Table as c where c.Database.id=" + (object)database.Id;
                IList<Table> tableList = session.CreateQuery(hql).List<Table>();

                if (tableList != null && tableList.Count > 0)
                {
                    foreach (Table table in tableList)
                    {
                        hql = "from Property as c where c.Table.id=" + (object)table.Id;
                        IList<Property> propertyList = session.CreateQuery(hql).List<Property>();
                        foreach (Property property in propertyList)
                        {
                            session.Delete(property);
                        }


                        hql = "from Grab as c where c.Table.id=" + (object)table.Id;
                        IList<Grab> grabList = session.CreateQuery(hql).List<Grab>();
                        foreach (Grab grab in grabList)
                        {
                            session.Delete(grab);
                        }

                        session.Delete(table);
                    }
                }
                session.Delete(database);
                session.Flush();
            }
        }
    }
}
